package com.smile.service.handler;

import com.smile.service.config.mqtt.handler.AbstractFlightAreasGetHandler;
import com.smile.service.entity.requests.FlightAreasGetEntity;
import com.smile.service.entity.services.BaseServicesEntity;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.UUID;

@Component
public class DefaultFlightAreasGetHandler extends AbstractFlightAreasGetHandler {


    @Override
    public Boolean process(String data, String tid, String bid,String gateway) throws MqttException {

        FlightAreasGetEntity flightAreasGetEntity = new FlightAreasGetEntity();
        FlightAreasGetEntity.Output output = new FlightAreasGetEntity.Output();
        output.setFiles(new ArrayList<>());
        flightAreasGetEntity.setOutput(output);
        flightAreasGetEntity.setResult(0);
        BaseServicesEntity<FlightAreasGetEntity> baseServicesEntity = new BaseServicesEntity<>();
        baseServicesEntity.setMethod("flight_areas_get");
        baseServicesEntity.setBid(UUID.randomUUID().toString());
        baseServicesEntity.setTid(tid);
        baseServicesEntity.setTimestamp(System.currentTimeMillis());
        baseServicesEntity.setData(flightAreasGetEntity);

        MqttMessage message = new MqttMessage();
        message.setQos(0);
        message.setRetained(true);
        message.setPayload(com.alibaba.fastjson2.JSONObject.toJSONString(baseServicesEntity).getBytes());
        MqttClient mqttClient = new MqttClient("tcp://120.211.119.131:1883", "feisuan-mqtt-producer-client", new MemoryPersistence());
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setUserName("feisuan");
        connOpts.setPassword("feisuan123456".toCharArray());
        mqttClient.connect(connOpts);

        mqttClient.publish("thing/product/" + gateway + "/requests_reply", message);
//        mqttClient.close();
        return true;
    }
}
